from django.shortcuts import render,HttpResponseRedirect,HttpResponse
from django.http import JsonResponse
from django.views import View
from .models import *
from .forms import *
from cart.cartmanager import *
# Create your views here.
class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')

    def post(self, request):
        # 获取所有请求参数以字典形式存储
        datas = request.POST.dict()

        # 进行表单数据校验
        register_form = RegiterForm(datas)

        # 判断是否校验成功
        if register_form.is_valid():
            user = User.register(**register_form.cleaned_data)
            request.session['user'] = user.account  # redis

            # print
            # request.session
            return HttpResponseRedirect('/user/usercenter/')

        else:

            return render(request, 'register.html', {'errors': register_form.errors, 'info': datas})

# 跳转到个人中心
class CenterView(View):
    def get(self,request):
        # 购物车迁移
        SessionCartManager(request.session).migrateSession2DB()
        return render(request,'usercenter.html')

# 退出登录
class LogoutView(View):
    def post(self,request):
        if 'user' in request.session:
            del request.session['user']
        return JsonResponse({'Flag':True})

class LoginView(View):
    def get(self,request):
        #获取登录后需要跳转的路径
        redirect = request.GET.get('redirect','')
        #获取购物项
        cartitems = request.GET.get('cartitems')
        return render(request,'login.html',{'redirect':redirect,'cartitems':cartitems})

    def post(self,request):
        try:

            user = User.login(**request.POST.dict())
            request.session['user'] = user.account

            #登录成功后页面进行相应的跳转

            if request.POST.get('redirect')=='cart':
                return HttpResponseRedirect('/cart/cart.html')
            elif request.POST.get('redirect')=='order':
                return HttpResponseRedirect('/order?cartitems='+request.POST.get('cartitems'))

            return HttpResponseRedirect('/user/usercenter/')

        except UserNotExistException:
            #没有登录成功就跳转至登录页面
            return render(request,'login.html')

from utils import code
# 生成验证码
class CodeView(View):
    def get(self,request):
        img,str= code.gene_code()
        request.session['sessioncode']=str
        return HttpResponse(img,content_type='image/png')

# 校验验证码
class CheckCodeView(View):
    def get(self,request):
        code = request.GET.get('code',None)
        scode = request.session.get('sessioncode','-1')
        # 将验证码中的大写字母转换为小写字母,使验证码不区分大小写
        result = code.lower() == scode.lower()
        return JsonResponse({'checkFlag':result})

from utils.loadaddr import *

class AddressView(View):
    def get(self,request):
        provinces = get_provinces()
        return render(request,'address.html',{'provinces':provinces})

    def post(self, request):
        type = request.POST.get('type', '1')
        if type == '1':
            provinceId = request.POST.get('provinceId')
            citys, areas = get_citys_areas_by_provinceid(provinceId)
            return JsonResponse({'citys': citys, 'areas': areas})


        elif type == '2':

            cityId = request.POST.get('cityId')

            areas = get_areas_by_cityid(cityId)

            return JsonResponse({'areas': areas})

        elif type == '3':
            html = '''<div id='dizhi'><p>{name}</p><p>{phone}</p><p>{address}</p><p>{details}</p></div>'''
            name = request.POST['name']

            phone = request.POST['phone']

            address = request.POST['address']

            user = User.objects.get(account=request.session.get('user'))

            # User().address_set.count()
            if user.address_set.count() == 0:
                isdefault = True
            else:
                isdefault = False

            Address.objects.create(uname=name, phone=phone, address=address, user=user,isdefault=isdefault)

            addresses = []

            for address1 in user.address_set.all():
                name = address1.uname

                phone = address1.phone

                address, details = (lambda a: (''.join(a[:-1]), ''.join(a[-1])))(address1.address.split(','))

                addresses.append(html.format(name=name, phone=phone, address=address, details=details))

            return JsonResponse({'addresses': addresses})